import React, { useState, useRef } from 'react';
import './FaceAnalysis.css';

/**
 * 面相分析页面组件
 */
const FaceAnalysis = () => {
  // 状态管理
  const [selectedImage, setSelectedImage] = useState(null);
  const [previewUrl, setPreviewUrl] = useState('');
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [analysisResult, setAnalysisResult] = useState(null);
  const [error, setError] = useState('');
  const [history, setHistory] = useState([]);
  const [activeTab, setActiveTab] = useState('analyze'); // 'analyze' or 'history'
  
  // DOM引用
  const fileInputRef = useRef(null);
  
  // 处理图片选择
  const handleImageChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      // 验证文件类型
      if (!file.type.match('image.*')) {
        setError('请选择图片文件');
        return;
      }
      
      // 验证文件大小 (最大5MB)
      if (file.size > 5 * 1024 * 1024) {
        setError('图片大小不能超过5MB');
        return;
      }
      
      setSelectedImage(file);
      setPreviewUrl(URL.createObjectURL(file));
      setError('');
    }
  };
  
  // 触发文件选择
  const triggerFileSelect = () => {
    fileInputRef.current.click();
  };
  
  // 移除已选择的图片
  const removeImage = () => {
    setSelectedImage(null);
    setPreviewUrl('');
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };
  
  // 模拟分析过程
  const analyzeFace = async () => {
    if (!selectedImage) {
      setError('请先选择一张面部照片');
      return;
    }
    
    setIsAnalyzing(true);
    setError('');
    
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 3000));
      
      // 生成模拟分析结果
      const mockResult = generateMockAnalysis();
      setAnalysisResult(mockResult);
      setActiveTab('result');
    } catch (err) {
      setError('分析失败，请稍后重试');
    } finally {
      setIsAnalyzing(false);
    }
  };
  
  // 生成模拟分析结果
  const generateMockAnalysis = () => {
    // 面部特征词库
    const eyebrowShapes = ['柳叶眉', '剑眉', '一字眉', '八字眉', '弯月眉'];
    const eyeShapes = ['杏眼', '丹凤眼', '桃花眼', '瑞凤眼', '龙眼'];
    const noseShapes = ['悬胆鼻', '狮子鼻', '露孔鼻', '蒜头鼻', '鹰钩鼻'];
    const lipShapes = ['樱桃小嘴', '薄唇', '厚唇', '元宝唇', '尖桃唇'];
    const faceShapes = ['瓜子脸', '鹅蛋脸', '方圆脸', '长方脸', '菱形脸'];
    
    // 性格特质词库
    const personalityTraits = [
      '聪明机智，思维敏捷',
      '性格温和，待人友善',
      '意志坚定，目标明确',
      '富有创造力，想象力丰富',
      '善于交际，人缘极佳',
      '责任心强，做事认真',
      '乐观开朗，积极向上',
      '细致入微，注重细节'
    ];
    
    // 职业建议词库
    const careerAdvice = [
      '适合从事创意类工作，如设计、艺术等',
      '在管理岗位上能发挥出色领导才能',
      '教育行业非常适合您的性格特点',
      '金融投资领域有很好的发展潜力',
      '适合从事技术类工作，如IT、工程等',
      '在服务行业能展现您的亲和力优势',
      '创业经商有很好的发展前景',
      '适合从事研究类工作，如学术、科研等'
    ];
    
    // 感情建议词库
    const relationshipAdvice = [
      '在感情中较为主动，容易吸引异性',
      '重视家庭和谐，是理想的伴侣',
      '需要在感情中多一些包容和理解',
      '容易遇到志同道合的人生伴侣',
      '在感情中需要保持适度的独立性',
      '善于沟通，能处理复杂的感情问题',
      '对感情忠诚专一，值得信赖',
      '需要学会表达内心真实感受'
    ];
    
    // 健康建议词库
    const healthRecommendations = [
      '注意保护眼睛，避免过度用眼',
      '保持良好的作息习惯，避免熬夜',
      '适当运动，增强体质',
      '注意饮食均衡，少食辛辣',
      '保持心情愉悦，避免情绪波动',
      '定期体检，关注心血管健康',
      '注意保暖，预防感冒',
      '多喝水，促进新陈代谢'
    ];
    
    // 幸运颜色词库
    const luckyColors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFBE0B', '#FB5607', '#8338EC', '#3A86FF'];
    
    // 随机生成分析结果
    const randomIndex = (arr) => Math.floor(Math.random() * arr.length);
    
    return {
      id: Date.now().toString(),
      imageUrl: previewUrl,
      overallScore: Math.floor(Math.random() * 40) + 60, // 60-100分
      overallImpression: `您的面相呈现出${faceShapes[randomIndex(faceShapes)]}的特征，整体气质优雅，给人留下深刻印象。`,
      facialFeatures: {
        faceShape: {
          name: faceShapes[randomIndex(faceShapes)],
          description: `您拥有典型的${faceShapes[randomIndex(faceShapes)]}，这种脸型在传统面相学中被认为是福相，象征着智慧与温和。`
        },
        eyebrows: {
          shape: eyebrowShapes[randomIndex(eyebrowShapes)],
          description: `您的${eyebrowShapes[randomIndex(eyebrowShapes)]}形状优美，眉形清晰，在面相学中代表智慧和判断力。`
        },
        eyes: {
          shape: eyeShapes[randomIndex(eyeShapes)],
          description: `您的${eyeShapes[randomIndex(eyeShapes)]}明亮有神，透露出聪慧和敏锐的洞察力。`
        },
        nose: {
          shape: noseShapes[randomIndex(noseShapes)],
          description: `您的${noseShapes[randomIndex(noseShapes)]}挺拔端正，象征着财运和事业运的良好发展。`
        },
        lips: {
          shape: lipShapes[randomIndex(lipShapes)],
          description: `您的${lipShapes[randomIndex(lipShapes)]}形态优美，代表您在人际关系和表达能力方面具有天赋。`
        }
      },
      personalityTraits: [
        personalityTraits[randomIndex(personalityTraits)],
        personalityTraits[randomIndex(personalityTraits)],
        personalityTraits[randomIndex(personalityTraits)]
      ],
      careerAdvice: careerAdvice[randomIndex(careerAdvice)],
      relationshipAdvice: relationshipAdvice[randomIndex(relationshipAdvice)],
      healthRecommendations: healthRecommendations[randomIndex(healthRecommendations)],
      luckyColor: luckyColors[randomIndex(luckyColors)],
      luckyNumber: Math.floor(Math.random() * 10) + 1,
      analysisTime: new Date().toLocaleString()
    };
  };
  
  // 保存分析结果
  const saveAnalysis = () => {
    if (analysisResult) {
      // 这里应该调用API保存结果
      alert('分析结果已保存！');
      // 更新历史记录
      setHistory(prev => [analysisResult, ...prev]);
    }
  };
  
  // 获取历史记录（模拟）
  const fetchHistory = () => {
    // 模拟获取历史记录
    const mockHistory = Array.from({ length: 5 }, (_, i) => ({
      id: `history-${i}`,
      overallScore: Math.floor(Math.random() * 40) + 60,
      analysisTime: new Date(Date.now() - i * 24 * 60 * 60 * 1000).toLocaleString(),
      imageUrl: 'https://via.placeholder.com/150'
    }));
    setHistory(mockHistory);
  };
  
  // 组件挂载时获取历史记录
  React.useEffect(() => {
    fetchHistory();
  }, []);
  
  return (
    <div className="face-analysis-page">
      {/* 页面标题 */}
      <header className="page-header">
        <h1>面相分析</h1>
        <p>通过AI技术分析您的面部特征，揭示性格与命运奥秘</p>
      </header>
      
      {/* 标签页导航 */}
      <div className="tabs">
        <button 
          className={`tab ${activeTab === 'analyze' ? 'active' : ''}`}
          onClick={() => setActiveTab('analyze')}
        >
          面相分析
        </button>
        <button 
          className={`tab ${activeTab === 'result' && analysisResult ? 'active' : ''}`}
          onClick={() => analysisResult && setActiveTab('result')}
          disabled={!analysisResult}
        >
          分析结果
        </button>
        <button 
          className={`tab ${activeTab === 'history' ? 'active' : ''}`}
          onClick={() => setActiveTab('history')}
        >
          我的历史
        </button>
      </div>
      
      {/* 内容区域 */}
      <main className="content-area">
        {/* 面相分析面板 */}
        {activeTab === 'analyze' && (
          <div className="analysis-panel">
            <div className="upload-section">
              <h2>上传面部照片</h2>
              <p className="instructions">
                请上传一张清晰的正面免冠照片，确保面部完全可见，无遮挡物。
              </p>
              
              <div className="upload-container">
                {previewUrl ? (
                  <div className="image-preview">
                    <img src={previewUrl} alt="预览" />
                    <button className="remove-btn" onClick={removeImage}>
                      移除图片
                    </button>
                  </div>
                ) : (
                  <div className="upload-placeholder" onClick={triggerFileSelect}>
                    <div className="upload-icon">📷</div>
                    <p>点击选择图片</p>
                    <p className="file-info">支持 JPG、PNG 格式，大小不超过 5MB</p>
                  </div>
                )}
                
                <input
                  type="file"
                  ref={fileInputRef}
                  onChange={handleImageChange}
                  accept="image/*"
                  style={{ display: 'none' }}
                />
              </div>
              
              {error && <div className="error-message">{error}</div>}
              
              <button 
                className="analyze-btn"
                onClick={analyzeFace}
                disabled={isAnalyzing || !selectedImage}
              >
                {isAnalyzing ? '分析中...' : '开始分析'}
              </button>
            </div>
            
            <div className="features-info">
              <h3>面相分析功能介绍</h3>
              <ul>
                <li>.faces-feature 面部特征识别：精确识别五官特征</li>
                <li>性格特质分析：揭示内在性格特点</li>
                <li>事业发展方向：提供职业规划建议</li>
                <li>感情关系指导：分析人际交往模式</li>
                <li>健康养生建议：根据面相提供保健指导</li>
                <li>幸运元素预测：找出您的幸运颜色和数字</li>
              </ul>
            </div>
          </div>
        )}
        
        {/* 分析结果面板 */}
        {activeTab === 'result' && analysisResult && (
          <div className="result-panel">
            <div className="result-header">
              <h2>面相分析报告</h2>
              <div className="result-score">
                <span className="score-label">综合评分</span>
                <span className="score-value">{analysisResult.overallScore}</span>
              </div>
            </div>
            
            <div className="result-content">
              {/* 整体印象 */}
              <section className="result-section">
                <h3>整体印象</h3>
                <p className="overall-impression">{analysisResult.overallImpression}</p>
              </section>
              
              {/* 面部特征分析 */}
              <section className="result-section">
                <h3>面部特征分析</h3>
                <div className="facial-features">
                  <div className="feature-item">
                    <h4>脸型</h4>
                    <p className="feature-name">{analysisResult.facialFeatures.faceShape.name}</p>
                    <p className="feature-desc">{analysisResult.facialFeatures.faceShape.description}</p>
                  </div>
                  <div className="feature-item">
                    <h4>眉毛</h4>
                    <p className="feature-name">{analysisResult.facialFeatures.eyebrows.shape}</p>
                    <p className="feature-desc">{analysisResult.facialFeatures.eyebrows.description}</p>
                  </div>
                  <div className="feature-item">
                    <h4>眼睛</h4>
                    <p className="feature-name">{analysisResult.facialFeatures.eyes.shape}</p>
                    <p className="feature-desc">{analysisResult.facialFeatures.eyes.description}</p>
                  </div>
                  <div className="feature-item">
                    <h4>鼻子</h4>
                    <p className="feature-name">{analysisResult.facialFeatures.nose.shape}</p>
                    <p className="feature-desc">{analysisResult.facialFeatures.nose.description}</p>
                  </div>
                  <div className="feature-item">
                    <h4>嘴唇</h4>
                    <p className="feature-name">{analysisResult.facialFeatures.lips.shape}</p>
                    <p className="feature-desc">{analysisResult.facialFeatures.lips.description}</p>
                  </div>
                </div>
              </section>
              
              {/* 性格特质 */}
              <section className="result-section">
                <h3>性格特质</h3>
                <ul className="personality-traits">
                  {analysisResult.personalityTraits.map((trait, index) => (
                    <li key={index} className="trait-item">✨ {trait}</li>
                  ))}
                </ul>
              </section>
              
              {/* 事业发展建议 */}
              <section className="result-section">
                <h3>事业发展建议</h3>
                <p className="career-advice">{analysisResult.careerAdvice}</p>
              </section>
              
              {/* 感情关系指导 */}
              <section className="result-section">
                <h3>感情关系指导</h3>
                <p className="relationship-advice">{analysisResult.relationshipAdvice}</p>
              </section>
              
              {/* 健康养生建议 */}
              <section className="result-section">
                <h3>健康养生建议</h3>
                <p className="health-recommendations">{analysisResult.healthRecommendations}</p>
              </section>
              
              {/* 幸运元素 */}
              <section className="result-section">
                <h3>今日幸运元素</h3>
                <div className="lucky-elements">
                  <div className="lucky-item">
                    <span className="lucky-label">幸运颜色</span>
                    <div 
                      className="lucky-color" 
                      style={{ backgroundColor: analysisResult.luckyColor }}
                    >
                      {analysisResult.luckyColor}
                    </div>
                  </div>
                  <div className="lucky-item">
                    <span className="lucky-label">幸运数字</span>
                    <span className="lucky-number">{analysisResult.luckyNumber}</span>
                  </div>
                </div>
              </section>
            </div>
            
            <div className="result-actions">
              <button className="save-btn" onClick={saveAnalysis}>
                保存结果
              </button>
              <button 
                className="re-analyze-btn" 
                onClick={() => {
                  setActiveTab('analyze');
                  removeImage();
                }}
              >
                重新分析
              </button>
            </div>
          </div>
        )}
        
        {/* 历史记录面板 */}
        {activeTab === 'history' && (
          <div className="history-panel">
            <h2>我的分析历史</h2>
            {history.length > 0 ? (
              <div className="history-list">
                {history.map((record) => (
                  <div key={record.id} className="history-item">
                    <div className="history-image">
                      <img src={record.imageUrl} alt="历史记录" />
                    </div>
                    <div className="history-details">
                      <div className="history-score">
                        <span className="score-label">评分</span>
                        <span className="score-value">{record.overallScore}</span>
                      </div>
                      <div className="history-date">
                        {record.analysisTime}
                      </div>
                      <button 
                        className="view-btn"
                        onClick={() => {
                          // 模拟查看历史记录详情
                          const mockDetail = generateMockAnalysis();
                          mockDetail.id = record.id;
                          setAnalysisResult(mockDetail);
                          setActiveTab('result');
                        }}
                      >
                        查看详情
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="no-history">
                <p>暂无分析历史记录</p>
                <button 
                  className="start-analysis-btn"
                  onClick={() => setActiveTab('analyze')}
                >
                  开始首次分析
                </button>
              </div>
            )}
          </div>
        )}
      </main>
    </div>
  );
};

export default FaceAnalysis;